﻿using MySql.Data.MySqlClient;
using System.Data;

namespace MeetingManagement.Application.Queries;

public abstract class QueryBase<T> where T : QuerySettings
{
    protected T Settings { get; private set; }
    protected QueryBase(T settings)
    {
        Settings = settings;
    }

    protected TOut Execute<TOut>(Func<IDbConnection, TOut> func)
    {
        using (var connection = new MySqlConnection(Settings.ConnectionString))
        {
            return func.Invoke(connection);
        }
    }

    protected async Task<TOut> ExecuteAsync<TOut>(Func<IDbConnection, Task<TOut>> func)
    {
        using (var connection = new MySqlConnection(Settings.ConnectionString))
        {
            return await func.Invoke(connection);
        }
    }
}

public abstract class QueryBase : QueryBase<QuerySettings>
{
    private readonly static string PAGINATION_SQL = @"SELECT * FROM ({0}) Temp LIMIT {1}, {2}; SELECT COUNT(1) FROM ({0}) TotalTmp;";
    protected QueryBase(QuerySettings settings) : base(settings)
    {
    }

    protected string BuildPaginationSql(string basicQuerySql, int pageNumber, int pageSize)
    {
        if (string.IsNullOrEmpty(basicQuerySql)) return string.Empty;
        if (pageSize <= 0) return string.Empty;

        var startOffset = pageNumber <= 0 ? 0 : (pageNumber - 1) * pageSize;

        return string.Format(PAGINATION_SQL, basicQuerySql, startOffset, pageSize);
    }
}
